<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.class_type"
        placeholder="类型"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in classType"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :loading="listLoading"
        @click="handleFilter"
      >搜索</el-button>
      <el-button v-waves :loading="readLoading" class="filter-item" type="primary" icon="el-icon-edit" @click="readAll">
        全部已读
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column type="index" width="60" align="center" sortable="custom" />
      <el-table-column label="类型" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag
            :type="row.class_type | statusFilter"
          >{{ classType[row.class_type]['display_name'] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">{{ readStatus[row.status]['display_name'] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center">
        <template slot-scope="{row}">
          <span>{{ row.class_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="问题概述" align="center">
        <template slot-scope="{row}">
          <span>{{ row.content | ellipsis }}</span>
        </template>
      </el-table-column>
      <el-table-column type="expand" label="详情" align="center" width="50">
        <template slot-scope="{row}">
          <div>
            {{ row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_time | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button v-if="row.status !== 2" size="mini" icon="el-icon-edit" type="success" @click="read(row.id)">已读</el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { fetchList, fetchRead, fetchReadAll, fetchDelete } from '@/api/studentQuestions'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { classType, readStatus } from '@/utils/dataType'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'StudentQuestions',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '1': 'warning',
        '2': 'success'
      }
      return statusMap[status]
    },
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 30) {
        return value.slice(0, 10) + '...'
      }
      return value
    },
    dateFormat(time) {
      return parseTime(time, '{y}-{m}-{d}')
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      roles: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10,
        class_type: undefined
      },
      classType,
      readStatus,
      user: {},
      dialogStatus: undefined,
      dialogLoading: false,
      downloadLoading: false,
      readLoading: false,
      dialogFormVisible: false
    }
  },
  created() {
    const id = this.$route.query.id
    if (id) {
      // 如果外链跳进来带有id，则把对应id的改成已读
      this.read(id)
    } else {
      this.getList()
    }
  },
  methods: {
    async getList() {
      try {
        this.listLoading = true
        const { data } = await fetchList(this.listQuery)
        const { data: list, total } = data;
        this.list = list;
        this.total = total;
        this.listLoading = false
      } catch (e) {
        this.listLoading = false
      }
    },
    async read(id) {
      try {
        await fetchRead(id)
        // this.$message({ message: '已读', type: 'success' })
        await this.getList()
      } catch (e) {
        console.log(e)
      }
    },
    async readAll() {
      try {
        this.readLoading = true
        await fetchReadAll()
        this.$message({ message: '成功', type: 'success' })
        await this.getList()
      } catch (e) {
        this.readLoading = false
      }
      this.readLoading = false
    },
    async del({ id }) {
      try {
        await fetchDelete(id)
        this.$message({ message: '删除成功', type: 'success' })
        await this.getList()
      } catch (e) {
        console.log(e)
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.order = '-id'
      } else {
        this.listQuery.order = '-id'
      }
      this.handleFilter()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
